package com.cyys.modules.core.initData;

import com.cyys.common.thirdInterface.ThirdConfig;
import com.cyys.modules.core.sysParam.*;
import com.cyys.modules.generator.service.GeneratorConfigureService;
import com.cyys.modules.system.service.configure.ConfigureService;
import com.cyys.modules.system.service.org.OrgService;
import com.cyys.modules.system.service.param.ParamBasicService;
import com.cyys.modules.system.service.param.ParamBasicTypeService;
import com.cyys.modules.system.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

@Component
@Order(1)
public class InitDataListener implements CommandLineRunner {
    private Logger log = LoggerFactory.getLogger(InitDataListener.class);

	@Resource
	private ParamBasicService paramBasicService;

	@Resource
	private ParamBasicTypeService paramBasicTypeService;

    @Resource
    private UserService userService;

    @Resource
	private ConfigureService configureService;

	@Resource
	private GeneratorConfigureService generatorConfigureService;

	@Resource
	private OrgService orgService;

    @Autowired
    ServletContext servletContext;

	@Override
	public void run(String... args) throws Exception {
		SystemConfigureUtil.init(configureService);
		//初始化系统名称、系统默认省份code、版本号
    	servletContext.setAttribute(SystemConstants.SYSTEM_NAME, SystemConfigureUtil.get(SystemConstants.SYSTEM_NAME));
		servletContext.setAttribute(SystemConstants.SYSTEM_PROVINCE_CODE, SystemConfigureUtil.get(SystemConstants.SYSTEM_PROVINCE_CODE));
    	servletContext.setAttribute(SystemConstants.FILE_VERSION, SystemConfigureUtil.get(SystemConstants.FILE_VERSION));
		//是否开启多机构
		servletContext.setAttribute(SystemConstants.MUTI_ORG, Boolean.valueOf(SystemConfigureUtil.get(SystemConstants.MUTI_ORG)));
		//文件web地址
		servletContext.setAttribute(SystemConstants.FILE_WEB_PATH, SystemConfigureUtil.get(SystemConstants.FILE_WEB_PATH));

		//高德地图version和key
		servletContext.setAttribute("GD_MAP_VERSION", ThirdConfig.GD_MAP_VERSION);
		servletContext.setAttribute("GD_MAP_KEY", ThirdConfig.GD_MAP_KEY);
		try {
			ParamBasicUtil.initParamBasic(paramBasicService);
			ParamBasicUtil.initParamBasicType(paramBasicTypeService);

			//多机构初始化
			if(SystemConfigureUtil.get(SystemConstants.MUTI_ORG).equals("true")) {
				OrgUtil.init(orgService);
				log.info("初始化机构数据:" + OrgUtil.getAll().size());
			}
			UserUtil.init(userService);
			log.info("初始化用户数据:" + UserUtil.getAll().size());

			/************代码生成器设置初始化*************/
			GeneratorUtil.init(generatorConfigureService);
			log.info("初始化代码生成器设置");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("初始化参数失败");
		}
        log.info("initSpring");
	}
}  